<template>
  <el-drawer :title="dialogTitle" size="60%"  v-model="dialogVisible">
    <el-form
      style="margin-right: 20px"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="上级栏目">
            <el-tree-select
              v-model="formData.parentId"
              :data="categoryTree"
              :default-expanded-keys="[0]"
              :props="defaultProps"
              check-strictly
              node-key="id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="属性" prop="propertySet">
            <el-select
              v-model="formData.propertySet"
              multiple
              collapse-tags
              placeholder="请选择属性"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CMS_CATEGORY_PROPERTY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CMS_CATEGORY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="栏目模板" prop="template">
            <el-select v-model="formData.template" placeholder="请选择栏目模板">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CMS_CATEGORY_TEMPLATE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="内容模板" prop="contentTemplate">
            <el-select v-model="formData.contentTemplate" placeholder="请选择内容模板">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CMS_CATEGORY_CONTENT_TEMPLATE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="内容类型" prop="contentType">
            <el-select v-model="formData.contentType" placeholder="请选择内容类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CMS_CATEGORY_CONTENT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="副名称" prop="subName">
            <el-input v-model="formData.subName" placeholder="请输入副名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="栏目key" prop="categoryKey">
            <el-input v-model="formData.categoryKey" placeholder="请输入栏目key" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模块key" prop="moduleKey">
            <el-input v-model="formData.moduleKey" placeholder="请输入模块key" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="拼音" prop="pinyin">
            <el-input v-model="formData.pinyin" placeholder="请输入拼音" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关键字" prop="keywords">
            <el-input v-model="formData.keywords" placeholder="请输入关键字" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="路径" prop="path">
            <el-input v-model="formData.path" placeholder="请输入路径" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="链接地址" prop="linkUrl">
            <el-input v-model="formData.linkUrl" placeholder="请输入链接地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <template #label>
              <Tooltip
                message="开启后可添加文章内容"
                title="状态"
              />
            </template>
            <el-radio-group v-model="formData.status">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否显示" prop="visible">
            <template #label>
              <Tooltip message="是否显示在网站前端" title="是否显示" />
            </template>
            <el-radio-group v-model="formData.visible">
              <el-radio key="true" :label="true" border>显示</el-radio>
              <el-radio key="false" :label="false" border>隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否搜索" prop="isSearch">
            <template #label>
              <Tooltip message="前端是否可以搜索该栏目内容" title="是否搜索" />
            </template>
            <el-radio-group v-model="formData.isSearch">
              <el-radio key="true" :label="true" border>是</el-radio>
              <el-radio key="false" :label="false" border>否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="banner图">
            <UploadImg v-model="formData.banner" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图标">
            <UploadImg v-model="formData.ico" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述">
        <el-input type="textarea" v-model="formData.description" height="250px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions, getDictOptions, getIntDictOptions } from '@/utils/dict'
import { CategoryApi, CategoryVO } from '@/api/cms/category'
import { defaultProps, handleTree } from '@/utils/tree'
import { CommonStatusEnum } from '@/utils/constants'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: 0,
  propertySet: [],
  type: undefined,
  name: undefined,
  subName: undefined,
  categoryKey: undefined,
  moduleKey: undefined,
  description: undefined,
  pinyin: undefined,
  banner: undefined,
  ico: undefined,
  keywords: undefined,
  path: undefined,
  linkUrl: undefined,
  template: undefined,
  contentTemplate: undefined,
  contentType: undefined,
  sort: Number(0),
  visible: false,
  isSearch: false,
  status: CommonStatusEnum.ENABLE
})
const formRules = reactive({
  parentId: [{ required: true, message: '父ID不能为空', trigger: 'change' }],
  propertySet: [{ required: true, message: '属性不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  categoryKey: [{ required: true, message: '栏目key不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '顺序不能为空', trigger: 'blur' }],
  visible: [{ required: true, message: '是否显示不能为空', trigger: 'blur' }],
  isSearch: [{ required: true, message: '是否搜索不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CategoryApi.getCategory(id)
      console.table(formData.value)
    } finally {
      formLoading.value = false
    }
  }
  // 获得列表
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {

    const data = formData.value as unknown as CategoryVO
    if (formType.value === 'create') {
      await CategoryApi.createCategory(data)
      message.success(t('common.createSuccess'))
    } else {
      await CategoryApi.updateCategory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 获取下拉框[上级栏目]的数据  */
const queryParams = reactive({
  status: undefined
})
const categoryTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  categoryTree.value = []
  const res = await CategoryApi.getCategoryList(queryParams)
  let category: Tree = { id: 0, name: '主类目', children: [] }
  category.children = handleTree(res)
  categoryTree.value.push(category)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: 0,
    propertySet: [],
    type: undefined,
    name: undefined,
    subName: undefined,
    categoryKey: undefined,
    moduleKey: undefined,
    description: undefined,
    pinyin: undefined,
    banner: undefined,
    ico: undefined,
    keywords: undefined,
    path: undefined,
    linkUrl: undefined,
    template: undefined,
    contentTemplate: undefined,
    contentType: undefined,
    sort: Number(0),
    visible: false,
    isSearch: false,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}
</script>
